
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
 class TreeNode {
    int val = 0;
   TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
      this.val = val;
   }
  }

public class test5 {
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        // write code here
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (pRoot == null) {
            return list;
        }
        TreeNode cur = pRoot;
        stack.push(cur);
        while (cur != null || !stack.isEmpty()) {
            ArrayList<Integer> temp = new ArrayList<>();
            int size = stack.size();
            while (size > 0) {
                TreeNode cut = stack.pop();
                temp.add(cut.val);
                if (cur.left != null) {
                    stack.push(cur);
                }
                if (cur.right != null) {
                    stack.push(cur);
                }
                size--;
            }
            list.add(temp);
        }
        return list;
    }
}
